﻿using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using TabbedTemplate.Models;
using Xamarin.Essentials;

namespace TabbedTemplate.Services
{
    public class LocationService : ILocationService
    {
        // ******** 私有变量
        /// <summary>
        /// 百度AK
        /// </summary>
        private const string BaiduAK = "qj44X3tjKlOpqmORGXCfzMfdNMhhnS0G";

        /// <summary>
        /// 获取地理位置副
        /// </summary>
        private IGeoLocationService _geoLocationService;

        // ******** 构造函数
        public LocationService(IGeoLocationService geoLocationService)
        {
            _geoLocationService = geoLocationService;
        }

        /// <summary>
        /// 获取用户当前位置
        /// </summary>
        /// <returns></returns>
        public async Task<Position> GetCurrentLocation()
        {
            var position = await _geoLocationService.GetLocationAsync();
            return position;
        }

        public class AddressComponent
        {

            public string city { get; set; }

        }

        public class Result
        {

            public AddressComponent addressComponent { get; set; }

        }

        public class Root
        {
            public Result result { get; set; }
        }

        /// <summary>
        /// 获取当前用户城市
        /// </summary>
        /// <param name="position"></param>
        /// <returns></returns>
        public async Task<string> GetCityByPosition(Position position)
        {
            using var httpClient = new HttpClient();
            HttpResponseMessage response;
            try
            {
                response = await httpClient.GetAsync(
                    "http://api.map.baidu.com/reverse_geocoding/v3/?ak=" +
                    BaiduAK + "&output=json&coordtype=wgs84ll&location=" +
                    position.Latitude + "," + position.Longitude);
                response.EnsureSuccessStatusCode();
            }
            catch (Exception e)
            {
                throw e;
            }

            var json = await response.Content.ReadAsStringAsync();

            var Root = JsonConvert.DeserializeObject<Root>(json);
            return Root.result.addressComponent.city;
        }

        public string CalculateDistance(Position p1, Position p2)
        {
            Location p1Location = new Location(p1.Latitude, p1.Longitude);
            Location p2Location = new Location(p2.Latitude, p2.Longitude);
            string res = Convert.ToString(Math.Round(
                Location.CalculateDistance(p1Location, p2Location,
                    DistanceUnits.Kilometers), 1));
            return res;
        }
    }
}
